<script lang="ts" setup>
import { reactive, ref, watch } from "vue"
import { getMerchantDataApi, updateMerchantApi, setMerchantSeqNoApi } from "@/api/merchant-manage"
import { type MerchantData, type UpdateMerchantRequestData } from "@/api/merchant-manage/types/merchant"
import { type FormInstance, type FormRules, ElMessage, ElMessageBox } from "element-plus"
import { Search, Refresh, Download, RefreshRight, Star } from "@element-plus/icons-vue"
import { usePagination } from "@/hooks/usePagination"
import { cloneDeep } from "lodash-es"

defineOptions({
  // 命名当前组件
  name: "MerchantInfo"
})

const loading = ref<boolean>(false)
const { paginationData, handleCurrentChange, handleSizeChange } = usePagination()

// 修改商户信息
const DEFAULT_FORM_DATA: UpdateMerchantRequestData = {
  id: 0,
  name: "",
  logo: "",
  canteenId: undefined,
  baseTime: undefined,
  minPrice: undefined,
  deliveryFee: undefined,
  address: "",
  licenseImage: "",
  shopImage: "",
  description: "",
  phone: "",
  latitude: undefined,
  longitude: undefined,
  supportDelivery: undefined,
  supportDineIn: undefined,
  supportTakeout: undefined
}

const dialogVisible = ref<boolean>(false)
const formRef = ref<FormInstance | null>(null)
const formData = ref<UpdateMerchantRequestData>(cloneDeep(DEFAULT_FORM_DATA))
const formRules: FormRules<UpdateMerchantRequestData> = {
  name: [{ required: true, trigger: "blur", message: "请输入商户名称" }],
  phone: [{ required: true, trigger: "blur", message: "请输入联系电话" }],
  address: [{ required: true, trigger: "blur", message: "请输入商户地址" }],
  baseTime: [{ required: true, trigger: "blur", message: "请输入备餐时长" }],
  minPrice: [{ required: true, trigger: "blur", message: "请输入起送价" }],
  deliveryFee: [{ required: true, trigger: "blur", message: "请输入配送费" }]
}

// 推荐设置相关
const recommendDialogVisible = ref<boolean>(false)
const recommendFormRef = ref<FormInstance | null>(null)
const recommendData = ref({
  merchantId: 0,
  merchantName: "",
  seqNo: 0,
  seqExpireDate: ""
})
const recommendRules: FormRules = {
  seqNo: [
    { required: true, trigger: "blur", message: "请输入排序号" },
    { type: "number", min: 1, max: 9999, trigger: "blur", message: "排序号范围为1-9999" }
  ],
  seqExpireDate: [
    { required: true, trigger: "change", message: "请选择排序失效日期" }
  ]
}

const handleUpdate = (row: MerchantData) => {
  dialogVisible.value = true
  formData.value = {
    id: row.id,
    name: row.name,
    logo: row.logo,
    canteenId: row.canteenId,
    baseTime: row.baseTime,
    minPrice: row.minPrice,
    deliveryFee: row.deliveryFee,
    address: row.address,
    licenseImage: row.licenseImage,
    shopImage: row.shopImage,
    description: row.description,
    phone: row.phone,
    latitude: row.latitude,
    longitude: row.longitude,
    supportDelivery: row.supportDelivery,
    supportDineIn: row.supportDineIn,
    supportTakeout: row.supportTakeout
  }
}

const handleRecommend = (row: MerchantData) => {
  recommendDialogVisible.value = true
  recommendData.value = {
    merchantId: row.id,
    merchantName: row.name,
    seqNo: row.seqNo || 0,
    seqExpireDate: ""
  }
}

const handleCancelRecommend = async (row: MerchantData) => {
  try {
    await ElMessageBox.confirm('您确定要取消推荐吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    await setMerchantSeqNoApi(row.id, 0)
    ElMessage.success('取消推荐成功')
    getMerchantData()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('取消推荐失败')
    }
  }
}

const handleUpdateSubmit = () => {
  formRef.value?.validate((valid: boolean, fields) => {
    if (!valid) return console.error("表单校验不通过", fields)
    loading.value = true
    updateMerchantApi(formData.value)
      .then(() => {
        ElMessage.success("修改成功")
        dialogVisible.value = false
        getMerchantData()
      })
      .finally(() => {
        loading.value = false
      })
  })
}

const handleRecommendSubmit = () => {
  recommendFormRef.value?.validate((valid: boolean, fields) => {
    if (!valid) return console.error("表单校验不通过", fields)
    loading.value = true
    
    // 格式化日期为 yyyy-MM-dd 格式
    let formattedDate = ""
    if (recommendData.value.seqExpireDate) {
      const date = new Date(recommendData.value.seqExpireDate)
      formattedDate = date.getFullYear() + '-' + 
                     String(date.getMonth() + 1).padStart(2, '0') + '-' + 
                     String(date.getDate()).padStart(2, '0')
    }
    
    setMerchantSeqNoApi(recommendData.value.merchantId, recommendData.value.seqNo, formattedDate || undefined)
      .then(() => {
        ElMessage.success("设置成功")
        recommendDialogVisible.value = false
        getMerchantData()
      })
      .finally(() => {
        loading.value = false
      })
  })
}

const resetForm = () => {
  formRef.value?.clearValidate()
  formData.value = cloneDeep(DEFAULT_FORM_DATA)
}

const resetRecommendForm = () => {
  recommendFormRef.value?.clearValidate()
  recommendData.value = {
    merchantId: 0,
    merchantName: "",
    seqNo: 0,
    seqExpireDate: ""
  }
}

// 查询商户信息数据
const merchantData = ref<MerchantData[]>([])
const searchFormRef = ref<FormInstance | null>(null)
const searchData = reactive({
  name: "",
  phone: "",
  status: ""
})

const getMerchantData = () => {
  loading.value = true
  getMerchantDataApi({
    pageNo: paginationData.currentPage,
    pageSize: paginationData.pageSize,
    name: searchData.name || undefined,
    phone: searchData.phone || undefined,
    status: searchData.status ? Number(searchData.status) : undefined
  })
    .then(({ data }) => {
      paginationData.total = data.total
      merchantData.value = data.list
    })
    .catch(() => {
      merchantData.value = []
    })
    .finally(() => {
      loading.value = false
    })
}

const handleSearch = () => {
  paginationData.currentPage === 1 ? getMerchantData() : (paginationData.currentPage = 1)
}

const resetSearch = () => {
  searchFormRef.value?.resetFields()
  handleSearch()
}

/** 监听分页参数的变化 */
watch([() => paginationData.currentPage, () => paginationData.pageSize], getMerchantData, { immediate: true })
</script>

<template>
  <div class="app-container">
    <el-card v-loading="loading" shadow="never" class="search-wrapper">
      <el-form ref="searchFormRef" :inline="true" :model="searchData">
        <el-form-item prop="name" label="商户名称">
          <el-input v-model="searchData.name" placeholder="请输入" />
        </el-form-item>
        <el-form-item prop="phone" label="联系电话">
          <el-input v-model="searchData.phone" placeholder="请输入" />
        </el-form-item>
        <el-form-item prop="status" label="营业状态">
          <el-select v-model="searchData.status" placeholder="请选择" clearable style="width: 100px;">
            <el-option label="休息中" value="0" />
            <el-option label="营业中" value="1" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :icon="Search" @click="handleSearch">查询</el-button>
          <el-button :icon="Refresh" @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    <el-card v-loading="loading" shadow="never">
      <div class="toolbar-wrapper">
        <div>
          <!-- 不需要新增和删除按钮 -->
        </div>
        <div>
          <el-tooltip content="下载">
            <el-button type="primary" :icon="Download" circle />
          </el-tooltip>
          <el-tooltip content="刷新当前页">
            <el-button type="primary" :icon="RefreshRight" circle @click="getMerchantData" />
          </el-tooltip>
        </div>
      </div>
      <div class="table-wrapper">
        <el-table :data="merchantData">
          <el-table-column prop="name" label="商户名称" align="center" />
          <el-table-column prop="logo" label="Logo" align="center">
            <template #default="scope">
              <el-image :src="scope.row.logo" style="width: 50px; height: 50px" fit="cover">
                <template #placeholder>
                  <el-icon>
                    <Picture />
                  </el-icon>
                </template>
                <template #error>
                  <el-icon>
                    <Loading />
                  </el-icon>
                </template>
              </el-image>
            </template>
          </el-table-column>
          <el-table-column prop="phone" label="联系电话" align="center" />
          <el-table-column prop="address" label="商户地址" align="center" />
          <el-table-column prop="rating" label="评分" align="center" />
          <el-table-column prop="sales" label="月销量" align="center" />
          <el-table-column prop="seqNo" label="排序号" align="center">
            <template #default="scope">
              <span>{{ scope.row.seqNo || 0 }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="seqExpireDate" label="排序失效日" align="center">
            <template #default="scope">
              <span v-if="scope.row.seqExpireDate">{{ scope.row.seqExpireDate }}</span>
              <span v-else style="color: #999;">-</span>
            </template>
          </el-table-column>
          <el-table-column prop="status" label="营业状态" align="center">
            <template #default="scope">
              <el-tag v-if="scope.row.status === 1" type="success" effect="plain" disable-transitions>营业中</el-tag>
              <el-tag v-else type="info" effect="plain" disable-transitions>休息中</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="createTime" label="创建时间" align="center" />
          <el-table-column fixed="right" label="操作" width="180" align="center">
            <template #default="scope">
              <div class="operation-buttons">
                <el-button type="primary" text bg size="small" @click="handleUpdate(scope.row)">修改</el-button>
                <el-button v-if="!scope.row.seqNo || scope.row.seqNo === 0" type="warning" text bg size="small" :icon="Star" @click="handleRecommend(scope.row)">推荐</el-button>
                <el-button v-else type="danger" text bg size="small" @click="handleCancelRecommend(scope.row)">取消推荐</el-button>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="pager-wrapper">
        <el-pagination
          background
          :layout="paginationData.layout"
          :page-sizes="paginationData.pageSizes"
          :total="paginationData.total"
          :page-size="paginationData.pageSize"
          :currentPage="paginationData.currentPage"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 修改商户信息 -->
    <el-dialog
      v-model="dialogVisible"
      title="修改商户信息"
      @closed="resetForm"
      width="40%"
    >
      <el-form ref="formRef" :model="formData" :rules="formRules" label-width="100px" label-position="left">
        <el-form-item prop="name" label="商户名称">
          <el-input v-model="formData.name" placeholder="请输入" />
        </el-form-item>
        <el-form-item prop="phone" label="联系电话">
          <el-input v-model="formData.phone" placeholder="请输入" />
        </el-form-item>
        <el-form-item prop="address" label="商户地址">
          <el-input v-model="formData.address" placeholder="请输入" />
        </el-form-item>
        <el-form-item prop="baseTime" label="备餐时长">
          <el-input-number v-model="formData.baseTime" :min="1" :max="60" placeholder="分钟" />
        </el-form-item>
        <el-form-item prop="minPrice" label="起送价">
          <el-input-number v-model="formData.minPrice" :min="0" :precision="2" :step="0.1" placeholder="元" />
        </el-form-item>
        <el-form-item prop="deliveryFee" label="配送费">
          <el-input-number v-model="formData.deliveryFee" :min="0" :precision="2" :step="0.1" placeholder="元" />
        </el-form-item>
        <el-form-item prop="description" label="商户描述">
          <el-input v-model="formData.description" type="textarea" :rows="3" placeholder="请输入" />
        </el-form-item>
        <el-form-item prop="supportDelivery" label="支持外卖">
          <el-radio-group v-model="formData.supportDelivery">
            <el-radio :label="1">是</el-radio>
            <el-radio :label="0">否</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item prop="supportDineIn" label="支持堂食">
          <el-radio-group v-model="formData.supportDineIn">
            <el-radio :label="1">是</el-radio>
            <el-radio :label="0">否</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item prop="supportTakeout" label="支持自取">
          <el-radio-group v-model="formData.supportTakeout">
            <el-radio :label="1">是</el-radio>
            <el-radio :label="0">否</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleUpdateSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 推荐设置弹框 -->
    <el-dialog
      v-model="recommendDialogVisible"
      title="设置商户推荐"
      @closed="resetRecommendForm"
      width="30%"
    >
      <div class="recommend-tip">
        <el-alert
          title="排序号越大越优先推荐"
          type="warning"
          :closable="false"
          show-icon
          style="margin-bottom: 20px;"
        />
      </div>
      <el-form ref="recommendFormRef" :model="recommendData" :rules="recommendRules" label-width="100px" label-position="left">
        <el-form-item label="商户名称">
          <el-input v-model="recommendData.merchantName" disabled />
        </el-form-item>
        <el-form-item prop="seqNo" label="推荐排序号">
          <el-input-number 
            v-model="recommendData.seqNo" 
            :min="1" 
            :max="9999" 
            placeholder="请输入排序号"
            style="width: 100%;"
          />
        </el-form-item>
        <el-form-item prop="seqExpireDate" label="排序失效日">
          <el-date-picker
            v-model="recommendData.seqExpireDate"
            type="date"
            placeholder="请选择失效日期"
            style="width: 100%;"
            :disabled-date="(time: Date) => time.getTime() < Date.now() - 8.64e7"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="recommendDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleRecommendSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<style lang="scss" scoped>
.search-wrapper {
  margin-bottom: 20px;
}

.toolbar-wrapper {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;
}

.table-wrapper {
  margin-bottom: 20px;
}

.pager-wrapper {
  display: flex;
  justify-content: center;
}

.operation-buttons {
  display: flex;
  gap: 8px;
  align-items: center;
  justify-content: center;
  white-space: nowrap;
  
  .el-button {
    margin: 0;
  }
}
</style>